<template>
    <div class="content-page">
        <div class="content-nav">
            <el-breadcrumb class="breadcrumb" separator="/">
                <el-breadcrumb-item :to="{ name: 'dashboard' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>数据管理</el-breadcrumb-item>
                <el-breadcrumb-item>分类管理</el-breadcrumb-item>
                <el-breadcrumb-item>{{infoForm.id ? '编辑分类' : '添加分类'}}</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="operation-nav">
                <el-button type="primary" @click="goBackPage" icon="arrow-left">返回列表</el-button>
            </div>
        </div>
        <div class="content-main">
            <div class="form-table-box">
                <el-form ref="infoForm" :rules="infoRules" :model="infoForm" label-width="120px">
                    <el-form-item label="上级分类" prop="path">
                        <el-cascader :options="category" v-model="infoForm.path"
                                     change-on-select :props="props"></el-cascader>
                    </el-form-item>
                    <el-form-item label="分类名称" prop="name">
                        <el-input v-model="infoForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="分类类型" prop="type">
                        <el-select v-model="infoForm.type" placeholder="请选择分类类型">
                            <el-option v-for="item in categoryType" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input-number v-model="infoForm.sort_order" :min="1" :max="1000" style="width: 240px"></el-input-number>
                    </el-form-item>
                    <el-form-item label="启用" prop="is_show">
                        <el-switch v-model="infoForm.is_show"></el-switch>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmitInfo">确定保存</el-button>
                        <el-button @click="goBackPage">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script>
// import api from '@/config/api'
export default {
  data () {
    return {
      uploaderHeader: {
        'X-Nideshop-Token': localStorage.getItem('token') || ''
      },
      category: [
        {
          id: 0,
          name: '顶级分类'
        }
      ],
      props: {
        value: 'id',
        label: 'name',
        children: 'child'
      },
      categoryType: [
        {
          id: 1,
          name: '宠物类'
        },
        {
          id: 2,
          name: '疾病类'
        }
      ],
      infoForm: {
        id: 0,
        name: '',
        type: 0,
        parent_id: 0,
        path: [0],
        sort_order: 100,
        is_show: true
      },
      infoRules: {
        path: [
          { required: true, message: '请输入分类', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入分类类型', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    goBackPage () {
      this.$router.go(-1)
    },
    onSubmitInfo () {
      this.$refs['infoForm'].validate((valid) => {
        if (valid) {
          this.infoForm.parent_id = this.infoForm.path[this.infoForm.path.length - 1]
          console.log(this.infoForm.parent_id)
          if (this.infoForm.id) {
            this.$db.category.update({id: this.infoForm.id}, this.infoForm, (err, count) => {
              if (err) console.error('kumeng: ' + err.stack)
              if (count) {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.$router.go(-1)
              }
            })
          } else {
            this.$db.category.find({}).projection({id: 1}).sort({id: -1}).exec((err, docs) => {
              if (err) console.error('kumeng: ' + err.stack)
              if (docs && docs.length) {
                this.infoForm.id = docs[0].id + 1
              } else {
                this.infoForm.id = 1
              }
              this.$db.category.insert(this.infoForm, (err, doc) => {
                if (err) console.error('kumeng: ' + err.stack)
                if (doc) {
                  this.$message({
                    type: 'success',
                    message: '增加成功'
                  })
                  this.$router.go(-1)
                }
              })
            })
          }
        } else {
          return false
        }
      })
    },
    async getCategory () {
      let top = await this.findCategoryWithParentId(0, 0)
      for (let i = 0; i < top.length; i++) {
        top[i].child = await this.findCategoryWithParentId(top[i].id, this.infoForm.type)
        if (top[i].child) {
          for (let j = 0; j < top[i].child.length; j++) {
            top[i].child[j].child = await this.findCategoryWithParentId(top[i].child[j].id, this.infoForm.type)
          }
        }
      }
      console.log('getCategory1: ' + JSON.stringify(top))
      this.category = this.category.concat(top)
    },
    async findCategoryWithParentId (parentId, type) {
      let query = {parent_id: parentId}
      if (type !== 0) query.type = type
      let result = await this.$db.category.asyncFind(query).then(docs => {
        if (docs && docs.length) {
          return docs
        }
      })
      return result
    },
    getInfo () {
      if (this.infoForm.id <= 0) {
        return false
      }

      // 加载分类详情
      this.$db.category.find({id: this.infoForm.id}, (err, docs) => {
        if (err) console.error('kumeng: ' + err.stack)
        if (docs && docs.length) {
          this.infoForm = docs[0]
        }
      })
    }

  },
  components: {},
  mounted () {
    this.getCategory()
    this.infoForm.id = this.$route.query.id || 0
    this.infoForm.type = this.$route.query.type || 0
    this.getInfo()
  }
}
</script>

<style>
    .image-uploader{
        height: 105px;
    }
    .image-uploader .el-upload {
        border: 1px solid #d9d9d9;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .image-uploader .el-upload:hover {
        border-color: #20a0ff;
    }

    .image-uploader .image-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        min-width: 105px;
        height: 105px;
        line-height: 105px;
        text-align: center;
    }

    .image-uploader .image-show {
        min-width: 105px;
        height: 105px;
        display: block;
    }

</style>
